import axios from 'axios';
import * as React from 'react';
import { history, useLocation } from 'umi';
import Good from '../component/good/Good';
import { FloatingBubble, SearchBar, Empty } from 'antd-mobile';
import { LeftOutline, UpOutline, DownFill } from 'antd-mobile-icons';
import './goods.less';
import {
  CaretUpOutlined,
  CaretDownOutlined,
  VerticalAlignTopOutlined,
} from '@ant-design/icons';

export interface IGoodsProps {}

let list: any[] = [];

export default function Goods(props: IGoodsProps) {
  let refs = React.useRef(null);
  let location = useLocation();
  let id = location.query.id || '';
  // 某类的数据
  const [data, setData] = React.useState<any[]>([]);
  // 控制小箭头的颜色
  const [change, setChange] = React.useState(false);
  const [hasMore, setHasMore] = React.useState(true);
  const [searchName, setSearchName] = React.useState(
    history.location.state || '',
  );
  function show() {
    console.log(searchName);
    axios
      .get('/api/home/search?classid=' + id + '&name=' + searchName)
      .then((res) => {
        console.log(res.data, '搜索');
        list = res.data.data;
        setData(res.data.data);
      });
  }
  React.useEffect(() => {
    // axios.get('/api/classify/getItem?id=' + id).then((res) => {
    //   console.log(res.data);
    //   list = res.data.data;
    //   setData(res.data.data);
    // });
    show();

    let one = '';
    setTimeout(() => {
      one = window.addEventListener('scroll', loadMore, true);
    }, 1000);

    return () => {
      window.removeEventListener('scroll', one);
    };
  }, []);
  // 价格排序
  function upPrice() {
    if (!change) {
      let list = data.sort((a, b) => {
        return a.price - b.price;
      });
      setData([...list]);
    } else {
      let list = data.sort((a, b) => {
        return b.price - a.price;
      });
      setData([...list]);
    }
    setChange(!change);
  }
  // 无限循环 触底加载
  let n = 1;
  function loadMore() {
    if (
      refs.current.clientHeight + refs.current.scrollTop >=
      refs.current.scrollHeight - 40
    ) {
      console.log(data, 'data');
      n++;
      let l: any[] = [];
      console.log(n);
      for (let index = 0; index < n; index++) {
        l = [...l, ...list];
      }
      setData([...l]);
    }
  }
  // 回到顶部
  function toTops() {
    // 可以回到顶部，但没有滚动的效果
    // refs.current.scrollTo(0,0)
    //  可以回到顶部，有滚动的效果
    let upTop = setInterval(() => {
      refs.current.scrollTop -= 300;
      if (refs.current.scrollTop === 0) {
        clearInterval(upTop);
      }
    }, 100);
  }

  return (
    <div className="goods">
      <div onClick={toTops}>
        <FloatingBubble
          axis="xy"
          magnetic="x"
          style={{
            '--initial-position-bottom': '24px',
            '--initial-position-right': '24px',
            '--edge-distance': '24px',
          }}
        >
          <UpOutline fontSize={32} />
        </FloatingBubble>
      </div>

      <div className="header">
        <LeftOutline
          fontSize={20}
          onClick={() => {
            history.goBack();
          }}
        />
        <SearchBar
          className="search"
          placeholder="请输入内容"
          value={searchName}
          clearOnCancel={true}
          style={{ '--background': '#ffffff', padding: ' 10px 5px' }}
          onChange={(value) => setSearchName(value)}
          onSearch={(value) => {
            console.log(value);
            setSearchName(value);
            show();
          }}
        />
      </div>
      <div ref={refs} className="bottom">
        <div className="top">
          <div>综合</div>
          <div>销量</div>
          <div className="price" onClick={() => upPrice()}>
            价格
            <div className="icon">
              <CaretUpOutlined
                // style={{ color: change ? '#1890ff' : '#1e1e1e' }}
                className={change ? 'up' : 'down'}
              />
              <CaretDownOutlined
                // style={{ color: !change ? '#1890ff' : '#1e1e1e' }}
                className={!change ? 'up' : 'down'}
              />
            </div>
          </div>
          <div>品牌</div>
          <div>筛选</div>
        </div>
        <div className="body">
          <>
            {data.length != 0 ? (
              data.map((item) => {
                return (
                  <Good
                    name={item.name}
                    price={item.price}
                    tag={item.tag}
                    desc={item.desc}
                    imgs={item.imgs}
                    id={item._id}
                    fid={item.classid}
                  ></Good>
                );
              })
            ) : (
              <Empty description="暂无商品" />
            )}
          </>
        </div>
      </div>
    </div>
  );
}
